import { WhitelistAddComponent } from './../whitelist-add/whitelist-add.component';
import { Component, OnInit, ChangeDetectorRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { map } from 'rxjs/operators';
import { MatDialog } from '@angular/material';
import { ToasterService } from '../../../share/services/toaster.service';
import { WhitelistService } from '../../services/whitelist.service';
import { RestrictedRecordOption, RestrictedRecord } from '../../services/restricted-record.service';
import { UsbAuthorizeService } from '../../services/usb-authorize.service';

@Component({
  selector: 'm-restricted-record',
  templateUrl: './restricted-record.component.html',
  styleUrls: ['./restricted-record.component.scss'],
})
export class RestrictedRecordComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private dialog: MatDialog,
    private service: UsbAuthorizeService,
    private toast: ToasterService,
    public changeDetectorRef: ChangeDetectorRef,
  ) {}

  activeAreaID: number;
  searchKey: string = '';
  areaList$ = this.route.data.pipe(map((data) => data['zone_list']));
  result$ = this.route.data.pipe(map((data) => data['list']));

  usbconf: any;
  ngOnInit() {
    this.service.getUsbConf().then((res: any) => {
      this.usbconf = +res.message;
    });
    this.route.queryParamMap.subscribe((data) => {
      this.activeAreaID = +(data.get('area_id') || 0);
      this.searchKey = data.get('keywords') || '';
    });
    this.service.usbEventer.subscribe((e) => {
      this.service.getUsbConf().then((res: any) => {
        this.usbconf = +res.message;
        this.changeDetectorRef.markForCheck();
        this.changeDetectorRef.detectChanges();
      });
    });
  }

  onActiveAreaID(id: number) {
    if (this.activeAreaID == id) {
      return;
    }
    this.activeAreaID = id;
    this.startSearch();
  }

  onSearchKey(key: string, exec: boolean) {
    if (this.searchKey == key) {
      return;
    }
    this.searchKey = key;
    if (!exec) {
      return;
    }
    this.startSearch();
  }

  startSearch() {
    let params: RestrictedRecordOption = { page: 1 };
    if (this.activeAreaID != 0) {
      params['area_id'] = this.activeAreaID;
    }
    if (this.searchKey.length != 0) {
      params['keywords'] = this.searchKey;
    }
    this.router.navigate([this.router.url.split('?')[0]], {
      relativeTo: this.route,
      queryParams: params,
    });
  }

  refresh() {
    return this.router.navigateByUrl(this.router.url);
  }

  addWhitelist(record: RestrictedRecord) {
    if (!record.vendor_id || !record.product_id || !record.serial_number) {
      this.toast.warn('只有“vendorID”、“ProductID”、“SerialNumber”都不为空才允许添加白名单。');
      return;
    }
    this.dialog.open(WhitelistAddComponent, { data: record });
  }

  async addAuthorization(record: RestrictedRecord) {
    if (!record.vendor_id || !record.product_id || !record.serial_number) {
      this.toast.warn('只有“vendorID”、“ProductID”、“SerialNumber”都不为空才允许添加授权。');
      return;
    }
    await this.service.modifyAuth({
      auth_type: Number(!record.is_authorized),
      whitelist_id: record.whitelist_id,
      pc_id: record.pc_id,
    });
    const msg = !record.is_authorized ? '已对该终端授权' : '已解除该终端授权';
    this.toast.success(msg);
    this.refresh();
  }
}
